
var express = require('express');
//用户数据库操作类
var User = require('../models/User');
//加载依赖类
var url = require('url');
//头像上传需要的upload类
var upload = require('../models/upload');
//用户发布信息需要的Post类
var Post = require('../models/post');
//需要引入一个加密的模块
var crypto = require('crypto');
//引入markdown模块
var markdown = require('markdown').markdown;
//验证
var validator = require('validator');
var DBSet = require('../models/db');
//时间格式化
var moment = require('moment');
//站点的配置
var settings = require('../models/db/settings');
var shortid = require('shortid');

//数据校验
var filter = require('../public/js/filter/filter');

//权限问题
//如果没有登录，直接跳转到登录页面
function checkLogin(req, res, next) {
    if (!req.session.user) {
        req.flash('error', '您还没有登录!');
        res.redirect('/login');
    }
    next();
}
//如果已经登录不能访问访问登录和注册页面的
function checkNotLogin(req, res, next) {
    if (req.session.user) {
        req.flash('error', '已登录!');
        res.redirect('back');//返回之前的页面
    }
    next();
}
function isLogined(req) {
    return req.session.logined;
}

module.exports = function (app) {
    //首页
    app.get('/', function (req, res) {
        res.render('index', {
            title: '主页',
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        })
    })
    //注册页
    app.get('/reg',checkNotLogin, function (req, res) {
        res.render('reg', {
            title: '注册',
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        })

    });
    //注册行为
    app.post('/reg',function (req,res,next) {
        var errors;
        var userName = req.body.userName;
        var email = req.body.email;
        var password = req.body.password;
        var confirmPsd = req.body.confirmPassword;
        //在服务器端再次验证数据格式
        if(!validator.matches(userName,/^[a-zA-Z][a-zA-Z0-9_]{2,11}$/)){
            errors = "用户名为3-12位只能包含字母、数字、或者字母数字组合";
        }
        if(!validator.matches(password,/^[?!a-zA-Z0-9_]{6,16}$/)){
            errors = "6-16位，只能包含字母数字下划线";
        }
        if(password != confirmPsd){
            errors = "密码不匹配，请重新输入";
        }
        if(!validator.isEmail(email)){
            errors = "请输入正确的邮箱地址";
        }
        if(errors){
            res.end(errors);
        } else {
            var regMsg = {
                email : email,
                username : userName
            };
            //邮箱和用户名必须唯一
            var query = User.find().or([{'email':email},{userName:userName}]);
            query.exec(function (err,user) {
                if(user.length > 0){
                    errors = "邮箱或者用户名已存在！";
                    res.end(errors);
                } else {
                    //密码加密
                    var newPsd = DBSet.encrypt(password,settings.encrypt_key);
                    req.body.password = newPsd;
                    DBSet.addOne(User,req,res);
                    res.end("success");
                }
            })
        }
    })

    //登录页
    app.get('/login',checkNotLogin, function (req, res) {
        res.render('login', {
            title: '登录',
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        })
    });
    //登录行为
    app.post('/login',function (req,res,next) {
        var userName = req.body.userName;
        var password = req.body.password;
        var newPsd = DBSet.encrypt(password,settings.encrypt_key);
        var errors;
        //在服务端再次验证表单的格式
        if(!validator.matches(userName,/^[a-zA-Z_][a-zA-Z0-9_]{2,11}$/)){
            errors = '用户名格式不正确';
        }
        if(!validator.matches(password,/^[?!a-zA-Z0-9_]{6,16}$/)){
            errors = '密码6-16个字符'
        }
        if(errors){
            res.end(errors);
        } else {
            User.findOne({userName:userName,password:newPsd},function (err,user) {
                if(user){
                    //将cookie存入缓存
                    filter.gen_session(user,res);
                    res.end('success');
                } else {
                    res.end('用户名或者密码错误!');
                }
            })
        }
    });
  //用户头像页面
  app.get('/userInfo',function (req, res,next) {
    res.render('userInfo', {
        title: '个人资料',
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString(),
        photo: 'upload/' + req.session.user.photo,
    })
});
// 用户头像上传操作
app.post('/userInfo',upload.single('photo'),function (req,res) {
        if(req.file){
            User.findByIdAndUpdate(req.session.user._id,{$set:{photo:'/upload/' + req.extension}},function(err,user){
                //如果发生了错误,跳转回首页
                if(err){
                    return res.redirect('/userInfo');
                }
                if(err){
                    return res.redirect('/users/userSetting');
                }
                req.flash("success","头像上传成功！")
                req.session.user = null;
                res.redirect('/');
                // });
            });
        }else{
            res.redirect('/userInfo');
        }
    });
  //修改
  app.get('/modify',function (req,res,next) {
    var params = url.parse(req.url,true);
    var currentId = params.query._id;
    res.render('modify',{
        title:'修改',
        logined:req.session.logined,
        userInfo:req.session.user,
        userInfoId:req.session.user._id,
        success: req.flash('success').toString(),
        error: req.flash('error').toString(),
        postId:currentId
    });
});
    //通过id获取一条具体的农产品信息
    app.get('/updatePost',function (req,res,next) {
        var params = url.parse(req.url,true);
        var currentId = params.query._id;
        Post.findOne({_id:currentId},function (err,post) {
            if(err){
                return res.end('error');
            } else {
                if(post){
                    return res.json(post);
                    console.log(post);
                } else {
                    return res.end('error');
                }
            }
        });
    });
    //修改行为
    app.post('/updatePost',function (req,res) {
        var errors;
        var selectName = req.body.selectName;
        var title = req.body.title;
        //再次在后台验证表单数据的正确
        if(!validator.isLength(title,0,10)){
            errors = '名称不得超过十个字！'
        }
        if(errors){
            res.end(errors);
        } else {
            Post.findByIdAndUpdate(req.body._id,req.body,function (err,result) {
                if ( err ) {
                   res.end('更新出错')
               } else {
                if(result){
                    res.end("success");
                } else {
                    res.end('更新失败');
                }
            }
        })
        }
    });
   
   //后台
   app.get('/backStage',function (req, res) {
    Post.find({},function(err,posts){
        var params = url.parse(req.url,true);
        var currentId = params.query._i
        res.render('backStage', {
            title: '后台',
            user: req.session.user,
            posts: posts,
            postId: currentId,
            success: req.flash('success').toString(),
            error: req.flash('error').toString(),
        });
    });  
});

  //市场行情页
  app.get('/market', function (req, res) {
    res.render('market', {
        title: '市场行情',
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
    });
});

    // 供应大厅
 app.get('/supply', function (req, res) {
        res.render('supply', {
            title: '供应大厅',
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        });
    });
    // 采购大厅
    app.get('/purchase', function (req, res) {
        Post.find({},function(err,posts){
           res.render('purchase', {
            title: '采购大厅',
            posts: posts,
            success: req.flash('success').toString(),
            error: req.flash('error').toString()
        });  
       });
    });
 // 发布信息页面
app.get('/post',checkLogin,function (req, res) {
        res.render('post', {
            title: '信息发布',
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString(),
        })
    });
//发布信息操作
app.post('/post',function (req,res) {
    var errors;
    var selectName = req.body.selectName;
    var title = req.body.title;
    var city = req.body.city;
    var price = req.body.price;
    var phone = req.body.phone;
        //再次在后台验证表单数据的正确
        if(!validator.isLength(title,0,10)){
            errors = '名称不得超过十个字！'
        }
        if(errors){
            res.end(errors);
        } else {
            req.body.users = req.session.user;
            var newObj = new Post(req.body);
            newObj.save(function(err){
                if(err){
                    res.end('error');
                }else{
                    User.update({userName:req.session.user.userName},function (err,result) {
                        if(result){
                            req.session.user = null;
                            res.end('success');
                        } else {
                            return res.end('error');
                        }
                    })
                }
            })
        }
    });
     // 删除
    app.get('/deletePost',function (req,res,next) {
        var params = url.parse(req.url,true);
        var currentId = params.query._id;
        console.log(currentId);
        Post.remove({_id:currentId},function (err,success) {
            if (err) {
                res.end('删除过程出错');
            } else {
                if(success){

                 res.redirect('/backStage');
             } else {
                res.end('删除失败！');
            }
        }
    })
    });
//商品详情页
app.get('/cuke',function (req, res) {
    res.render('cuke', {
        title: '商品详情',
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString(),
    })
})
 //搜索结果页面的路由
 app.get('/search',checkLogin, function (req, res) {
    var pattern = new RegExp(req.query.keyWord, "i");
    Post.find({title:pattern}).exec(function (err, post) {
        if (isLogined(req)) {
            if (err) {
                return res.redirect('/');
            }
            console.log(post);
            if( post[0] ){
                post.forEach(function (art) {
                    if(art.selectName === 'grain'){
                        art.selectName = '粮油米面'
                    } 
                    if(art.selectName === 'fruit'){
                        art.selectName = '水果蔬菜'
                    }
                    if(art.selectName === 'tree'){
                        art.selectName = '苗木花卉'
                    }
                    if(art.selectName === 'water'){
                        art.selectName = '畜牧水产'
                    }else{
                     art.selectName = '农资农机'
                    }
                });
                res.render('search', {
                    title: "搜索",
                    posts: post,
                    logined:isLogined(req),
                    userInfo:req.session.user,
                    userInfoId:req.session.user._id,
                    success: req.flash('success').toString(),
                    error: req.flash('error').toString(),
                    noResult:null
                });
            } else {
                res.render('search', {
                    title: "搜索",
                    posts: post,
                    logined:isLogined(req),
                    userInfo:req.session.user,
                    userInfoId:req.session.user._id,
                    success: req.flash('success').toString(),
                    error: req.flash('error').toString(),
                    noResult:'对不起,暂时没有您想要的商品看看别的吧！'
                });
            }
        } else {
            if (err) {
                return res.redirect('/');
            }
            if( post ){
                post.forEach(function (art) {
                   if(art.selectName === 'grain'){
                        art.selectName = '粮油米面'
                    } 
                    if(art.selectName === 'fruit'){
                        art.selectName = '水果蔬菜'
                    }
                    if(art.selectName === 'tree'){
                        art.selectName = '苗木花卉'
                    }
                    if(art.selectName === 'water'){
                        art.selectName = '畜牧水产'
                    }else{
                     art.selectName = '农资农机'
                    }
                })
                res.render('search', {
                    title: "搜索",
                    posts: post,
                    logined:isLogined(req),
                    userInfo:req.session.user,
                    success: req.flash('success').toString(),
                    error: req.flash('error').toString(),
                    userInfoId:null,
                    noResult:null
                });
            } else {
                res.render('search', {
                    title: "SEARCH:" + req.query.keyWord,
                    posts: post,
                    logined:isLogined(req),
                    userInfo:req.session.user,
                    userInfoId:null,
                    success: req.flash('success').toString(),
                    error: req.flash('error').toString(),
                    noResult:'对不起，没有您搜索的话题标题...'
                });
            }
        }
    });
    
});
 //退出
 app.get('/logout',checkLogin, function (req, res) {
    req.session.destroy();
    res.clearCookie(settings.auth_cookie_name);
    res.redirect('/');
})
};
